#! /usr/bin/env python
# -*- coding: utf-8 -*-


from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging


logging.basicConfig(level=logging.INFO, stream=sys.stdout)


class Cos(object):
    """
    腾讯云 COS
    """

    def __init__(self, secret_id, secret_key, region, token=None, scheme='https'):
        """
        初始化 Cos对象
        :param secret_id: 用户secret_id
        :param secret_key: 用户secret_key
        :param region: 用户region
        :param token: # 使用临时密钥需要传入 Token，默认为空，可不填
        :param scheme: # 指定使用 http/https 协议来访问 COS，默认为 https，可不填
        """

        self.secret_id = secret_id
        self.secret_key = secret_key
        self.region = region
        self.token = token
        self.scheme = scheme
        config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
        self.client = CosS3Client(config)

    def list_buckets(self):
        """
        查询当前账号下所有的存储桶
        :return: 桶列表Dict
        """
        return self.client.list_buckets()['Buckets']

    def create_bucket(self, bucket_name, **kwargs):
        """
        创建桶
        :param bucket_name: 桶名称，格式"bucket_name-APPID"
        :return: None
        """

        self.client.create_bucket(bucket_name, **kwargs)

    def delete_bucket(self, bucket_name, **kwargs):
        """
        创建桶
        :param bucket_name: 桶名称，格式"bucket_name-APPID"
        :return: None
        """
        self.client.delete_bucket(bucket_name, **kwargs)

    def upload_file(self, bucket_name, local_path, key, part_size=1, max_thread=5, enable_md5=False, **kwargs):
        """
        该高级接口根据用户文件的长度自动选择简单上传以及分块上传，对于小于等于20M的文件调用简单上传，
        对于大于20MB的文件调用分块上传，对于分块上传未完成的文件会自动进行断点续传。
        :param bucket_name: 桶名称
        :param local_path: 本地文件路径
        :param key: 对象键（Key）是对象在存储桶中的唯一标识
        :param part_size: 分块上传的分块大小，默认为1MB
        :param max_thread: 分块上传的并发数量，默认为5个线程上传分块
        :param enable_md5:是否需要 SDK 计算 Content-MD5，默认关闭，打开后会增加上传耗时
        :param kwargs: 其他参数查看官方文档 https://cloud.tencent.com/document/product/436/35151
        :return: 上传对象的 MD5 值
        """
        return self.client.upload_file(bucket_name, key, local_path, part_size, max_thread, enable_md5, **kwargs)['ETag']

    def get_object_acl(self, bucket_name, key, **kwargs):
        """
        获取对象信息
        :param bucket_name
        :param key:
        :param kwargs:
        :return: dict
        """
        return self.client.get_object_acl(bucket_name, key, **kwargs)

    def delete_object(self, bucket_name, key, **kwargs):
        """
        删除单个对象
        :param bucket_name:
        :param key:
        :param kwargs:
        :return: dict
        """
        return self.client.delete_object(bucket_name, key, **kwargs)

    def delete_objects(self, bucket_name, delete, **kwargs):
        """
        删除多个对象
        :param bucket_name:
        :param delete:
                        Delete={
                        'Object': [
                            {
                                'Key': 'exampleobject1',
                                'VersionId': 'string'
                            },
                            {
                                'Key': 'exampleobject2',
                                'VersionId': 'string'
                            },
                        ],
                        'Quiet': 'true'|'false'
                        #Quiet 指明删除的返回结果方式，可选值为 'true'，'false'，默认为 'false'。
                        设置为 'true' 只返回失败的错误信息，设置为 'false' 时返回成功和失败的所有信息
                    }
        :param kwargs:
        :return: dict
        """

        return self.client.delete_objects(bucket_name, delete, **kwargs)

    def get_object(self, bucket_name, key, local_path, **kwargs):
        """
        下载对象
        :param bucket_name:
        :param key:
        :param kwargs:
        :param local_path: 存放文件路径
        :return:
        """
        self.client.get_object(bucket_name, key)["Body"].get_stream_to_file(local_path)


